<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="检验计划编号" prop="planNo">
        <el-input
          v-model="queryParams.planNo"
          placeholder="请输入检验计划编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收料通知单编号" prop="receiptNoteNo">
        <el-input
          v-model="queryParams.receiptNoteNo"
          placeholder="请输入收料通知单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="送货单编号" prop="deliveryNoteNo">
        <el-input
          v-model="queryParams.deliveryNoteNo"
          placeholder="请输入送货单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="存货名称" prop="inventoryName">
        <el-input
          v-model="queryParams.inventoryName"
          placeholder="请输入存货名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="批次号" prop="batchNo">
        <el-input
          v-model="queryParams.batchNo"
          placeholder="请输入批次号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 质检状态切换：未质检 / 已质检 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="24">
        <el-radio-group v-model="statusFilter" size="mini" @change="handleStatusFilterChange">
          <el-radio-button label="PENDING">未质检</el-radio-button>
          <el-radio-button label="COMPLETED">已质检</el-radio-button>
        </el-radio-group>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="mb8">
      
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-if="statusFilter === 'COMPLETED'"
          v-hasPermi="['system:plan:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:plan:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:plan:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="60" align="center" />
      <el-table-column type="index" label="序号" width="70" align="center" />
      <el-table-column label="检验计划编号" align="center" prop="planNo" min-width="180" />
      <el-table-column label="收料通知单编号" align="center" prop="receiptNoteNo" min-width="180" />
      <el-table-column label="送货单编号" align="center" prop="deliveryNoteNo" min-width="180" />
      <el-table-column label="存货编码" align="center" prop="inventoryCode" min-width="160" />
      <el-table-column label="存货名称" align="center" prop="inventoryName" min-width="200" />
      <el-table-column label="批次号" align="center" prop="batchNo" min-width="160" />
      <el-table-column label="检验员" align="center" prop="inspector" min-width="140" />
      <el-table-column label="检验日期" align="center" prop="inspectionDate" min-width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.inspectionDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="260">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.planStatus === 'COMPLETED'"
            v-hasPermi="['system:plan:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:plan:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleInspect(scope.row)"
            v-if="statusFilter !== 'COMPLETED'"
            v-hasPermi="['system:plan:edit']"
          >检验</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改来料检验计划对话框：与检验弹窗一致的布局 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="editInspectFormRef" :model="editInspectForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="存货编码">
              <el-input v-model="editInspectForm.inventoryCode" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="存货名称">
              <el-input v-model="editInspectForm.inventoryName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="批次号">
              <el-input v-model="editInspectForm.batchNo" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合格数量">
              <el-input-number v-model="editInspectForm.qualifiedQuantity" :min="0" :controls="false" disabled style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="不合格数量">
              <el-input-number v-model="editInspectForm.rejectedQuantity" :min="0" :controls="false" disabled style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实际抽检数量">
              <el-input-number v-model="editInspectForm.sampleQuantityActual" :min="0" :controls="true" style="width: 100%" />
              <div style="color: #999; font-size: 12px; margin-top: 4px;">
                为避免卡顿，最多开启 {{ measureInputsMax }} 个字段输入。
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="检验员">
              <el-input v-model="editInspectForm.inspector" placeholder="请输入检验员" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否拒收">
              <el-select v-model="editInspectForm.rejectFlag" placeholder="请选择">
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="检验结果">
              <el-select v-model="editInspectForm.inspectionResult" placeholder="请选择">
                <el-option label="合格" value="合格" />
                <el-option label="不合格" value="不合格" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="center">不合格统计</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddDefectRow">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteDefectRow">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="defectStatsList" :row-class-name="rowDefectIndex" @selection-change="sel => { checkedDefectRows = sel.map(i => i.index) }" ref="defectStatsEdit">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="60" />
          <el-table-column label="不合格原因" prop="reason" width="600">
            <template slot-scope="scope">
              <el-input v-model="scope.row.reason" placeholder="请输入不合格原因" />
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="quantity" width="250" align="center">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.quantity" :min="0" />
            </template>
          </el-table-column>
        </el-table>

        <el-divider content-position="center">按指标检验</el-divider>
        <el-table :data="inspectionItemList">
          <el-table-column type="index" label="序号" width="70" align="center" />
          <el-table-column label="检验项目" prop="itemName" min-width="100" />
          <el-table-column label="验收标准" prop="acceptanceCriteria" min-width="180" />
          <el-table-column label="检验方法" prop="inspectionMethod" min-width="80" />
          <el-table-column label="标准值" prop="standardValue" min-width="60" />
          <el-table-column label="上限值" prop="upperLimit" min-width="60" />
          <el-table-column label="下限值" prop="lowerLimit" min-width="60" />
          <el-table-column
            v-for="i in 10"
            :key="i"
            :label="'字段' + i"
            min-width="80"
            align="center"
          >
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.measuredValues[i - 1]"
                :min="0"
                :controls="false"
                :disabled="(i - 1) >= getLimitedMeasureCountEdit()"
                style="width: 100%"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 来料检验弹窗：两列字段布局 + 不合格统计 + 按指标检验 -->
    <el-dialog :title="inspectTitle" :visible.sync="inspectOpen" width="1000px" append-to-body>
      <el-form ref="inspectFormRef" :model="inspectForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="存货编码">
              <el-input v-model="inspectForm.inventoryCode" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="存货名称">
              <el-input v-model="inspectForm.inventoryName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="批次号">
              <el-input v-model="inspectForm.batchNo" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合格数量">
              <el-input-number v-model="inspectForm.qualifiedQuantity" :min="0" :controls="false" disabled style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="不合格数量">
              <el-input-number v-model="inspectForm.rejectedQuantity" :min="0" :controls="false" disabled style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实际抽检数量">
              <el-input-number v-model="inspectForm.sampleQuantityActual" :min="0" :controls="true" style="width: 100%" />
              <div style="color: #999; font-size: 12px; margin-top: 4px;">
                为避免卡顿，最多开启 {{ measureInputsMax }} 个字段输入。
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="检验员">
              <el-input v-model="inspectForm.inspector" placeholder="请输入检验员" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否拒收">
              <el-select v-model="inspectForm.rejectFlag" placeholder="请选择">
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="检验结果">
              <el-select v-model="inspectForm.inspectionResult" placeholder="请选择">
                <el-option label="合格" value="合格" />
                <el-option label="不合格" value="不合格" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="center">不合格统计</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddDefectRow">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteDefectRow">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="defectStatsList" :row-class-name="rowDefectIndex" @selection-change="sel => { checkedDefectRows = sel.map(i => i.index) }" ref="defectStats">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="60" />
          <el-table-column label="不合格原因" prop="reason" width="600">
            <template slot-scope="scope">
              <el-input v-model="scope.row.reason" placeholder="请输入不合格原因" />
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="quantity" width="250" align="center">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.quantity" :min="0" />
            </template>
          </el-table-column>
        </el-table>

        <el-divider content-position="center">按指标检验</el-divider>
        <el-table :data="inspectionItemList">
          <el-table-column type="index" label="序号" width="70" align="center" />
          <el-table-column label="检验项目" prop="itemName" min-width="100" />
          <el-table-column label="验收标准" prop="acceptanceCriteria" min-width="180" />
          <el-table-column label="检验方法" prop="inspectionMethod" min-width="100">
            <template slot-scope="scope">
              <el-tag size="mini">{{ inspectionMethodDict[scope.row.inspectionMethod] || scope.row.inspectionMethod || '-' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="标准值" prop="standardValue" min-width="60" />
          <el-table-column label="上限值" prop="upperLimit" min-width="60" />
          <el-table-column label="下限值" prop="lowerLimit" min-width="60" />
          <el-table-column
            v-for="i in 10"
            :key="i"
            :label="'字段' + i"
            min-width="80"
            align="center"
          >
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.measuredValues[i - 1]"
                :min="0"
                :controls="false"
                :disabled="(i - 1) >= getLimitedMeasureCount()"
                style="width: 100%"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitInspect">提 交</el-button>
        <el-button @click="inspectOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPlan, getPlan, delPlan, addPlan, updatePlan } from "@/api/system/plan"
import { getTemplate, listTemplate } from "@/api/system/template"
import { listBarcode, updateBarcode } from "@/api/system/barcode"
import { updatePurchaseOrderItemStatus } from "@/api/system/purchase_order"

export default {
  name: "Plan",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedBizInspectionResult: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 来料检验计划表格数据
      planList: [],
      // 检验结果明细表格数据
      bizInspectionResultList: [],
      // —— 新增：检验弹窗 ——
      inspectOpen: false,
      inspectTitle: "",
      inspectForm: {
        inventoryCode: "",
        inventoryName: "",
        batchNo: "",
        qualifiedQuantity: 0,
        rejectedQuantity: 0,
        sampleQuantityActual: 0,
        inspector: "",
        rejectFlag: "否",
        inspectionResult: "合格",
        templateId: null,
        templateNo: null
      },
      // —— 新增：编辑弹窗采用与检验弹窗一致的布局与字段 ——
      editInspectForm: {
        inventoryCode: "",
        inventoryName: "",
        batchNo: "",
        qualifiedQuantity: 0,
        rejectedQuantity: 0,
        sampleQuantityActual: 0,
        inspector: "",
        rejectFlag: "否",
        inspectionResult: "合格",
        templateId: null,
        templateNo: null
      },
      defectStatsList: [],
      checkedDefectRows: [],
      inspectionItemList: [],
      // 最大测量输入框数量，防止页面卡顿
      measureInputsMax: 10,
      // 当前检验计划的总数量，用于计算合格数量
      inspectPlanTotalQuantity: 0,
      // 质检状态切换（PENDING 未质检 / COMPLETED 已质检）
      statusFilter: 'PENDING',
      // 原始列表数据，用于本地过滤
      allPlanRows: [],
      // 检验方法枚举映射
      inspectionMethodDict: {
        VISUAL: '目视',
        MEASUREMENT: '测量',
        TEST: '测试',
        VERIFICATION: '验证',
        // 兼容模板中的历史枚举值
        DIMENSIONAL: '测量',
        PERFORMANCE: '测试',
        SAFETY: '验证'
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planNo: null,
        receiptNoteNo: null,
        deliveryNoteNo: null,
        inventoryName: null,
        batchNo: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    }
  },
  created() {
    this.getList()
  },
  watch: {
    'inspectForm.sampleQuantityActual'(val) {
      this.syncMeasuredInputsLength()
    }
    ,
    'editInspectForm.sampleQuantityActual'(val) {
      this.syncMeasuredInputsLength()
    },
    // 深度监听不合格统计的数量变化，动态计算不合格与合格数量
    defectStatsList: {
      handler() {
        this.updateRejectAndQualified()
      },
      deep: true
    },
    // 切换质检视图时，本地过滤显示列表
    statusFilter() {
      this.planList = this.filterByStatus(this.allPlanRows)
    }
  },
  methods: {
    /** 查询来料检验计划列表 */
    getList() {
      this.loading = true
      listPlan(this.queryParams).then(response => {
        const rows = Array.isArray(response.rows) ? response.rows : []
        // 按创建时间倒序排序（兼容 createdTime 或 createTime 字段）
        const getTime = (r) => {
          const v = r.createdTime || r.createTime
          if (!v) return 0
          const t = new Date(v).getTime()
          return isNaN(t) ? 0 : t
        }
        this.allPlanRows = rows.slice().sort((a, b) => getTime(b) - getTime(a))
        this.planList = this.filterByStatus(this.allPlanRows)
        this.total = response.total
        this.loading = false
      })
    },
    /** 根据切换状态过滤显示的计划行（仅显示 PENDING 或 COMPLETED，排除 CANCELLED） */
    filterByStatus(rows) {
      const want = this.statusFilter
      return (rows || []).filter(r => {
        const s = r && r.planStatus
        if (want === 'PENDING') return s === 'PENDING'
        if (want === 'COMPLETED') return s === 'COMPLETED'
        return true
      })
    },
    /** 处理状态切换（可按需触发重新拉取或仅本地过滤） */
    handleStatusFilterChange() {
      this.planList = this.filterByStatus(this.allPlanRows)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        planId: null,
        planNo: null,
        receiptNoteId: null,
        receiptNoteNo: null,
        deliveryNoteNo: null,
        supplierCode: null,
        supplierName: null,
        inventoryCode: null,
        inventoryName: null,
        batchNo: null,
        totalBoxes: null,
        totalQuantity: null,
        sampleBoxes: null,
        sampleQuantity: null,
        templateId: null,
        templateNo: null,
        planStatus: null,
        inspector: null,
        inspectionDate: null,
        inspectionResult: null,
        qualifiedQuantity: null,
        rejectedQuantity: null,
        rejectionReason: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
        remark: null,
        delFlag: null
      }
      this.bizInspectionResultList = []
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.planId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加来料检验计划"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const planId = row.planId || this.ids
      getPlan(planId).then(response => {
        const p = response.data || {}
        this.form = p
        this.bizInspectionResultList = Array.isArray(p.bizInspectionResultList) ? p.bizInspectionResultList : []
        // 初始化编辑弹窗的两列布局字段（与检验弹窗一致）
        this.editInspectForm = {
          inventoryCode: p.inventoryCode || "",
          inventoryName: p.inventoryName || "",
          batchNo: p.batchNo || "",
          qualifiedQuantity: Number(p.qualifiedQuantity || 0),
          rejectedQuantity: Number(p.rejectedQuantity || 0),
          sampleQuantityActual: Number(p.sampleQuantity || 0),
          inspector: p.inspector || "",
          rejectFlag: p.rejectFlag || "否",
          inspectionResult: (p.inspectionResult === 'FAIL') ? '不合格' : '合格',
          templateId: p.templateId || null,
          templateNo: p.templateNo || null
        }
        // 打开编辑弹窗
        this.open = true
        this.title = "修改来料检验计划"
        // 解析模板ID并载入检验项目，同时按明细结果回填测量值
        this.resolveTemplateId(p).then(tid => {
          this.editInspectForm.templateId = tid
          if (tid) {
            this.loadInspectionItemsWithResults(tid, this.bizInspectionResultList)
          }
        })
      })
    },
    /** 行级检验按钮操作：打开新增检验结果弹窗 */
    handleInspect(row) {
      const planId = row.planId
      if (!planId) {
        this.$modal.msgError("未找到该行的计划ID")
        return
      }
      getPlan(planId).then(response => {
        const p = response.data || {}
        // 保留原始表单用于提交更新（含 planId、planNo等）
        this.form = p
        // 记录当前计划的总数量，用于后续计算合格数量
        this.inspectPlanTotalQuantity = Number(p.totalQuantity || 0)
        // 初始化检验弹窗表单（两列布局字段）
        this.inspectForm = {
          inventoryCode: p.inventoryCode || "",
          inventoryName: p.inventoryName || "",
          batchNo: p.batchNo || "",
          qualifiedQuantity: 0,
          rejectedQuantity: 0,
          sampleQuantityActual: Number(p.sampleQuantity || 0),
          inspector: p.inspector || "",
          rejectFlag: "否",
          inspectionResult: "合格",
          templateId: p.templateId || null
        }
        // 清空不合格统计与指标检验数据
        this.defectStatsList = []
        this.inspectionItemList = []
        // 打开检验弹窗
        this.inspectOpen = true
        this.inspectTitle = "来料检验"
        // 初始化计算一次不合格与合格数量
        this.updateRejectAndQualified()
        // 解析模板ID并载入方案的检验项目（按 itemNo 正序）
        this.resolveTemplateId(p).then(tid => {
          this.inspectForm.templateId = tid
          if (tid) {
            this.loadInspectionItems(tid)
          } else {
            this.$modal.msgWarning("未找到对应检验方案，按指标检验无数据")
          }
        })
      })
    },
    /** 依据不合格统计计算不合格数量与合格数量 */
    updateRejectAndQualified() {
      const sumRejected = (this.defectStatsList || []).reduce((acc, cur) => {
        const n = Number(cur && cur.quantity)
        return acc + (isNaN(n) ? 0 : n)
      }, 0)
      this.inspectForm.rejectedQuantity = sumRejected
      this.editInspectForm.rejectedQuantity = sumRejected
      const total = Number(this.inspectPlanTotalQuantity || this.form.totalQuantity || 0)
      let qualified = total - sumRejected
      if (isNaN(qualified) || qualified < 0) qualified = 0
      this.inspectForm.qualifiedQuantity = qualified
      this.editInspectForm.qualifiedQuantity = qualified
    },
    /** 根据模板ID加载检验项目，并按项目序号正序排列 */
    loadInspectionItems(templateId) {
      getTemplate(templateId).then(resp => {
        const data = resp.data || {}
        // 绑定模板编号，便于提交时写回计划
        this.inspectForm.templateNo = data.templateNo || this.inspectForm.templateNo
        const items = Array.isArray(data.bizInspectionItemList) ? data.bizInspectionItemList : []
        this.inspectionItemList = items
          .slice()
          .sort((a, b) => Number(a.itemNo || 0) - Number(b.itemNo || 0))
          .map(it => ({
            itemId: it.itemId,
            itemNo: it.itemNo,
            itemName: it.itemName,
            acceptanceCriteria: it.acceptanceCriteria,
            inspectionMethod: it.inspectionMethod,
            standardValue: it.standardValue,
            upperLimit: it.upperLimit,
            lowerLimit: it.lowerLimit,
            measuredValues: Array(this.measureInputsMax).fill(null)
          }))
        if (!items.length) {
          this.$modal.msgWarning("该检验方案未配置检验项目，按指标检验为空")
        }
      })
    },
    /** 获取受限的测量输入框数量 */
    getLimitedMeasureCount() {
      const raw = parseInt(this.inspectForm.sampleQuantityActual || 0, 10)
      if (isNaN(raw) || raw < 0) return 0
      if (raw > this.measureInputsMax) return this.measureInputsMax
      return raw
    },
    /** 编辑弹窗：获取受限的测量输入框数量 */
    getLimitedMeasureCountEdit() {
      const raw = parseInt(this.editInspectForm.sampleQuantityActual || 0, 10)
      if (isNaN(raw) || raw < 0) return 0
      if (raw > this.measureInputsMax) return this.measureInputsMax
      return raw
    },
    /** 与抽检数量同步：确保每行的字段数组长度固定为10 */
    syncMeasuredInputsLength() {
      const max = this.measureInputsMax
      this.inspectionItemList = this.inspectionItemList.map(row => {
        const current = Array.isArray(row.measuredValues) ? row.measuredValues.slice() : []
        if (current.length < max) {
          return { ...row, measuredValues: current.concat(Array(max - current.length).fill(null)) }
        }
        if (current.length > max) {
          return { ...row, measuredValues: current.slice(0, max) }
        }
        return row
      })
    },
    /** 根据模板ID加载检验项目，并按明细结果回填测量值 */
    loadInspectionItemsWithResults(templateId, results) {
      getTemplate(templateId).then(resp => {
        const data = resp.data || {}
        // 绑定模板编号到编辑表单
        this.editInspectForm.templateNo = data.templateNo || this.editInspectForm.templateNo
        const items = Array.isArray(data.bizInspectionItemList) ? data.bizInspectionItemList : []
        const grouped = {}
        const arr = Array.isArray(results) ? results : []
        arr.forEach(r => {
          const key = (r && (r.itemId || r.itemNo))
          if (!key) return
          if (!grouped[key]) grouped[key] = []
          const v = r.actualValue
          if (v !== null && v !== undefined && v !== "") grouped[key].push(v)
        })
        this.inspectionItemList = items
          .slice()
          .sort((a, b) => Number(a.itemNo || 0) - Number(b.itemNo || 0))
          .map(it => {
            const key = it.itemId || it.itemNo
            const values = grouped[key] || []
            const mv = Array(this.measureInputsMax).fill(null)
            for (let i = 0; i < Math.min(values.length, this.measureInputsMax); i++) {
              mv[i] = values[i]
            }
            return {
              itemId: it.itemId,
              itemNo: it.itemNo,
              itemName: it.itemName,
              acceptanceCriteria: it.acceptanceCriteria,
              inspectionMethod: it.inspectionMethod,
              standardValue: it.standardValue,
              upperLimit: it.upperLimit,
              lowerLimit: it.lowerLimit,
              measuredValues: mv
            }
          })
        if (!items.length) {
          this.$modal.msgWarning("该检验方案未配置检验项目，按指标检验为空")
        }
      })
    },
    /** 根据计划解析模板ID，若缺失则通过模板编号查询 */
    resolveTemplateId(p) {
      if (p && p.templateId) return Promise.resolve(p.templateId)
      if (p && p.templateNo) {
        const q = { templateNo: p.templateNo, pageNum: 1, pageSize: 1 }
        return listTemplate(q).then(r => {
          const rows = Array.isArray(r.rows) ? r.rows : []
          return rows.length ? rows[0].templateId : null
        })
      }
      // 回退：按存货编码尝试查询模板
      if (p && p.inventoryCode) {
        const q2 = { inventoryCode: p.inventoryCode, pageNum: 1, pageSize: 1 }
        return listTemplate(q2).then(r2 => {
          const rows2 = Array.isArray(r2.rows) ? r2.rows : []
          return rows2.length ? rows2[0].templateId : null
        })
      }
      return Promise.resolve(null)
    },
    /** 不合格统计添加一行 */
    handleAddDefectRow() {
      this.defectStatsList.push({ reason: "", quantity: 0 })
      this.updateRejectAndQualified()
    },
    /** 不合格统计删除选中行 */
    handleDeleteDefectRow() {
      if (this.checkedDefectRows.length === 0) {
        this.$modal.msgError("请先选择要删除的不合格统计行")
        return
      }
      const ids = this.checkedDefectRows
      this.defectStatsList = this.defectStatsList.filter(item => ids.indexOf(item.index) === -1)
      this.checkedDefectRows = []
      this.updateRejectAndQualified()
    },
    /** 不合格统计序号 */
    rowDefectIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 检验弹窗提交（将指标检验的数字合并为结果列表后更新计划） */
    submitInspect() {
      // 将指标检验的测量值展平为 bizInspectionResultList
      const compiled = []
      const overallPass = this.inspectForm.inspectionResult === '合格'
      const resultCode = overallPass ? 'PASS' : 'FAIL'
      const qualityStatus = overallPass ? 'QUALITY_PASSED' : 'QUALITY_FAILED'
      const currentUser = (this.$store && this.$store.state && this.$store.state.user && this.$store.state.user.name) ? this.$store.state.user.name : ''
      const limitCount = this.getLimitedMeasureCount()
      this.inspectionItemList.forEach(item => {
        const values = Array.isArray(item.measuredValues) ? item.measuredValues : []
        values.forEach((val, idx) => {
          if (idx >= limitCount) return
          if (val === null || val === undefined || val === "") return
          // 生成明细行：补齐必填字段
          const nowDateStr = this.parseTime ? this.parseTime(new Date(), '{y}-{m}-{d}') : (new Date()).toISOString().slice(0, 10)
          compiled.push({
            resultId: null,
            planId: this.form.planId,
            planNo: this.form.planNo || "",
            itemId: item.itemId,
            itemNo: item.itemNo,
            itemName: item.itemName,
            inspectionMethod: item.inspectionMethod,
            acceptanceCriteria: item.acceptanceCriteria,
            standardValue: item.standardValue,
            upperLimit: item.upperLimit,
            lowerLimit: item.lowerLimit,
            actualValue: val,
            result: resultCode,
            inspector: this.inspectForm.inspector || currentUser || "",
            inspectionTime: nowDateStr,
            createdBy: currentUser || this.inspectForm.inspector || 'system',
            createdTime: nowDateStr
          })
        })
      })
      // 更新计划的基本检验信息（按需求写回）
      this.form.inspector = this.inspectForm.inspector || this.form.inspector
      this.form.sampleQuantity = this.inspectForm.sampleQuantityActual
      this.form.inspectionResult = resultCode
      this.form.planStatus = 'COMPLETED'
      this.form.inspectionDate = new Date()
      this.form.qualifiedQuantity = this.inspectForm.qualifiedQuantity
      this.form.rejectedQuantity = this.inspectForm.rejectedQuantity
      this.form.rejectionReason = (this.defectStatsList || [])
        .map(r => (r && r.reason) ? String(r.reason).trim() : '')
        .filter(Boolean)
        .join('; ')
      // 模板ID与编号写回计划
      this.form.templateId = this.inspectForm.templateId || this.form.templateId
      this.form.templateNo = this.inspectForm.templateNo || this.form.templateNo
      // 明细结果（最多十个，且仅取开放的前N个值）
      this.form.bizInspectionResultList = compiled
      updatePlan(this.form).then(() => {
        // 提交成功后，批量更新该批次所有箱码的质量结果与关联明细状态
        const batchNo = this.inspectForm.batchNo || this.form.batchNo
        if (!batchNo) {
          this.$modal.msgWarning("未找到批次号，跳过箱码与采购明细状态更新")
          this.inspectOpen = false
          this.getList()
          return
        }
        return this.updateAllBarcodesAndItemsByBatch(batchNo, qualityStatus, resultCode).then(() => {
          this.$modal.msgSuccess("检验数据与状态已更新")
          this.inspectOpen = false
          this.getList()
        })
      }).catch(() => {
        this.$modal.msgError("提交检验数据失败")
      })
    },
    /**
     * 批量更新指定批次号的所有箱码质量结果，并同步所有关联采购明细状态
     */
    updateAllBarcodesAndItemsByBatch(batchNo, qualityStatus, resultCode) {
      const pageSize = 500
      const accumulate = []
      const fetchPage = (pageNum) => {
        return listBarcode({ batchNo, pageNum, pageSize }).then(res => {
          const rows = Array.isArray(res.rows) ? res.rows : []
          const total = Number(res.total || rows.length || 0)
          accumulate.push(...rows)
          const totalPages = Math.max(1, Math.ceil(total / pageSize))
          if (pageNum < totalPages && rows.length > 0) {
            return fetchPage(pageNum + 1)
          }
        })
      }
      return fetchPage(1).then(() => {
        if (!accumulate.length) {
          this.$modal.msgWarning("未匹配到该批次号的箱码记录")
          return
        }
        // 统一更新所有箱码质量结果与检验信息
        const planNo = this.form.planNo
        const inspectedTime = new Date()
        const updateTasks = accumulate.map(bc => {
          const payload = {
            barcodeId: bc.barcodeId,
            qualityResult: resultCode,
            barcodeStatus: 'INSPECTED',
            inspectionPlanNo: planNo || bc.inspectionPlanNo,
            inspectedTime
          }
          return updateBarcode(payload)
        })
        // 收集去重后的 itemId 并更新对应采购明细状态
        const itemIds = Array.from(new Set(accumulate.map(bc => bc.itemId).filter(Boolean)))
        const itemTasks = itemIds.map(id => updatePurchaseOrderItemStatus(id, qualityStatus))
        return Promise.all([...updateTasks, ...itemTasks])
      })
    },
    /** 提交按钮 */
    submitForm() {
      // 编辑弹窗采用与检验弹窗一致的按指标检验明细编译
      const overallPass = this.editInspectForm.inspectionResult === '合格'
      const resultCode = overallPass ? 'PASS' : 'FAIL'
      const currentUser = (this.$store && this.$store.state && this.$store.state.user && this.$store.state.user.name) ? this.$store.state.user.name : ''
      const limitCount = this.getLimitedMeasureCountEdit()
      const compiled = []
      this.inspectionItemList.forEach(item => {
        const values = Array.isArray(item.measuredValues) ? item.measuredValues : []
        values.forEach((val, idx) => {
          if (idx >= limitCount) return
          if (val === null || val === undefined || val === "") return
          const nowDateStr = this.parseTime ? this.parseTime(new Date(), '{y}-{m}-{d}') : (new Date()).toISOString().slice(0, 10)
          compiled.push({
            resultId: null,
            planId: this.form.planId,
            planNo: this.form.planNo || "",
            itemId: item.itemId,
            itemNo: item.itemNo,
            itemName: item.itemName,
            inspectionMethod: item.inspectionMethod,
            acceptanceCriteria: item.acceptanceCriteria,
            standardValue: item.standardValue,
            upperLimit: item.upperLimit,
            lowerLimit: item.lowerLimit,
            actualValue: val,
            result: resultCode,
            inspector: this.editInspectForm.inspector || currentUser || "",
            inspectionTime: nowDateStr,
            createdBy: currentUser || this.editInspectForm.inspector || 'system',
            createdTime: nowDateStr
          })
        })
      })
      // 写回计划的相关字段
      this.form.inspector = this.editInspectForm.inspector || this.form.inspector
      this.form.sampleQuantity = this.editInspectForm.sampleQuantityActual
      this.form.inspectionResult = resultCode
      // 保持计划状态不变（仅编辑），如需提交检验请使用检验弹窗
      this.form.qualifiedQuantity = Number(this.editInspectForm.qualifiedQuantity || 0)
      this.form.rejectedQuantity = Number(this.editInspectForm.rejectedQuantity || 0)
      this.form.rejectionReason = (this.defectStatsList || [])
        .map(r => (r && r.reason) ? String(r.reason).trim() : '')
        .filter(Boolean)
        .join('; ')
      this.form.templateId = this.editInspectForm.templateId || this.form.templateId
      this.form.templateNo = this.editInspectForm.templateNo || this.form.templateNo
      this.form.bizInspectionResultList = compiled

      const doUpdate = () => {
        if (this.form.planId != null) {
          updatePlan(this.form).then(() => {
            this.$modal.msgSuccess("修改成功")
            this.open = false
            this.getList()
          })
        } else {
          addPlan(this.form).then(() => {
            this.$modal.msgSuccess("新增成功")
            this.open = false
            this.getList()
          })
        }
      }
      // 若存在编辑表单校验，则先校验再提交
      const ref = this.$refs && this.$refs.editInspectFormRef
      if (ref && typeof ref.validate === 'function') {
        ref.validate(valid => { if (valid) doUpdate() })
      } else {
        doUpdate()
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const planIds = row.planId || this.ids
      this.$modal.confirm('是否确认删除来料检验计划编号为"' + planIds + '"的数据项？').then(function() {
        return delPlan(planIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
	/** 检验结果明细序号 */
    rowBizInspectionResultIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 检验结果明细添加按钮操作 */
    handleAddBizInspectionResult() {
      let obj = {}
      obj.planNo = ""
      obj.itemId = ""
      obj.itemNo = ""
      obj.itemName = ""
      obj.inspectionMethod = ""
      obj.acceptanceCriteria = ""
      obj.standardValue = ""
      obj.upperLimit = ""
      obj.lowerLimit = ""
      obj.actualValue = ""
      obj.result = ""
      obj.defectDescription = ""
      obj.inspector = ""
      obj.inspectionTime = ""
      obj.createdBy = ""
      obj.createdTime = ""
      this.bizInspectionResultList.push(obj)
    },
    /** 检验结果明细删除按钮操作 */
    handleDeleteBizInspectionResult() {
      if (this.checkedBizInspectionResult.length == 0) {
        this.$modal.msgError("请先选择要删除的检验结果明细数据")
      } else {
        const bizInspectionResultList = this.bizInspectionResultList
        const checkedBizInspectionResult = this.checkedBizInspectionResult
        this.bizInspectionResultList = bizInspectionResultList.filter(function(item) {
          return checkedBizInspectionResult.indexOf(item.index) == -1
        })
      }
    },
    /** 复选框选中数据 */
    handleBizInspectionResultSelectionChange(selection) {
      this.checkedBizInspectionResult = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/plan/export', {
        ...this.queryParams
      }, `plan_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
.measure-inputs {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
</style>
